<template>
  <div class="form-widget-container">
    <a-form v-if="data" :key="data.key" :model="data" layout="vertical">
      <a-form-item
        v-if="data.type !== 'grid'"
        label="字段名称"
        name="fieldName"
        :rules="{ required: true, message: '请输入字段名称', trigger: 'blur' }"
      >
        <a-input v-model:value="data.fieldName" />
      </a-form-item>

      <a-form-item v-if="data.type !== 'grid' && data.type !== 'fixedCombination'" label="提示信息">
        <a-input v-if="data.type !== 'text'" v-model:value="data.options.promptInfo" />
        <a-textarea v-else v-model:value="data.options.promptInfo" :rows="4" />
        <check-box-extend v-if="data.options.promptInfo" v-model:checked="data.options.hidePromptFlag">
          隐藏提示信息，鼠标悬浮时显示
        </check-box-extend>
        <check-box-extend v-if="data.type == 'text'" v-model:checked="data.options.showDivider">
          显示分割线
        </check-box-extend>
      </a-form-item>

      <a-form-item v-if="hasKey('placeholder')" label="占位提示">
        <a-input v-model:value="data.options.placeholder" :disabled="disabledAttr()" />
      </a-form-item>

      <a-form-item v-if="data.type !== 'upload'" label="属性" :rules="{ required: true }">
        <a-select
          v-model:value="data.options.attr"
          :get-popup-container="
            (triggerNode) => {
              return triggerNode.parentNode
            }
          "
          disabled
        >
          <a-select-option :value="1">业务字段</a-select-option>
          <a-select-option :value="2">自定义字段</a-select-option>
        </a-select>
      </a-form-item>

      <a-form-item v-if="data.type === 'number'" label="格式" :rules="{ required: true }">
        <a-select
          v-model:value="data.options.numericFormat"
          :get-popup-container="
            (triggerNode) => {
              return triggerNode.parentNode
            }
          "
          :disabled="disabledAttr()"
        >
          <a-select-option :value="1">数值</a-select-option>
          <a-select-option :value="2">货币</a-select-option>
        </a-select>
      </a-form-item>

      <a-form-item v-if="hasKey('options')" label="选项">
        <a-radio-group
          v-if="data.type === 'select' && isConfig()"
          v-model:value="data.options.remote"
          button-style="solid"
          :disabled="disabledAttr()"
          @change="remoteChange"
        >
          <a-radio-button :value="1">静态数据</a-radio-button>
          <a-radio-button :value="2">远端数据</a-radio-button>
        </a-radio-group>
        <a-space v-if="data.options.remote === 2" direction="vertical" style="margin-top: 10px">
          <a-input v-model:value="data.options.remoteConfig.url" addon-before="远端地址" :disabled="disabledAttr()" />
          <a-input
            v-model:value="data.options.remoteConfig.fullLabel"
            addon-before="标签模板"
            :disabled="disabledAttr()"
          />
          <a-input v-model:value="data.options.remoteConfig.labelKey" addon-before="标签" :disabled="disabledAttr()" />
          <a-input v-model:value="data.options.remoteConfig.valueKey" addon-before="值" :disabled="disabledAttr()" />
          <a-input
            v-if="data.type === 'treeSelect'"
            v-model:value="data.options.remoteConfig.children"
            addon-before="子选项"
            :disabled="disabledAttr()"
          />
          <check-box-extend
            v-if="data.type === 'select'"
            v-model:checked="data.options.multipleFlag"
            :disabled="disabledAttr()"
            @change="handleSelectModeChange"
          >
            允许选择多项
          </check-box-extend>
        </a-space>
        <template v-else>
          <template v-if="data.type === 'radio' || (data.type === 'select' && !data.options.multipleFlag)">
            <a-radio-group v-model:value="data.options.defaultValue" :disabled="disabledAttr()">
              <Draggable
                tag="ul"
                item-key="index"
                ghost-class="ghost"
                handle=".drag-item"
                :group="{ name: 'options' }"
                :list="data.options.options"
              >
                <template #item="{ element, index }">
                  <div>
                    <a-radio :value="element.value" style="margin-right: 0px">
                      <a-input
                        v-model:value="element.value"
                        size="small"
                        :style="{
                          width: '68px',
                          marginRight: '20px'
                        }"
                        :disabled="disabledAttr()"
                      />
                      <a-input
                        v-model:value="element.label"
                        size="small"
                        :style="{
                          width: '90px',
                          padding: '0 7px',
                          border: '1px solid #d9d9d9'
                        }"
                        :disabled="disabledAttr()"
                      />
                    </a-radio>
                    <template v-if="!disabledAttr()">
                      <SvgIcon
                        style="margin: 0; cursor: move"
                        name="item"
                        class="drag-item"
                        prefix="icon-form"
                        size="14"
                      />
                      <a-button
                        type="primary"
                        shape="circle"
                        size="small"
                        style="margin-left: 10px"
                        @click="handleOptionsRemove(index)"
                      >
                        <template #icon>
                          <SvgIcon name="delete" prefix="icon-form" color="#fff" size="14" />
                        </template>
                      </a-button>
                    </template>
                  </div>
                </template>
              </Draggable>
            </a-radio-group>
          </template>

          <template v-if="data.type === 'checkbox' || (data.type === 'select' && data.options.multipleFlag)">
            <a-checkbox-group v-model:value="data.options.defaultOptions" :disabled="disabledAttr()">
              <Draggable
                tag="ul"
                item-key="index"
                ghost-class="ghost"
                handle=".drag-item"
                :group="{ name: 'options' }"
                :list="data.options.options"
              >
                <template #item="{ element, index }">
                  <li>
                    <a-checkbox :value="element.value" style="margin-right: 0">
                      <a-input
                        v-model:value="element.value"
                        size="small"
                        :style="{
                          width: '90px'
                        }"
                        :disabled="disabledAttr()"
                      />
                      <a-input
                        v-model:value="element.label"
                        size="small"
                        :style="{
                          width: '90px',
                          padding: '0 7px',
                          border: '1px solid #d9d9d9'
                        }"
                        :disabled="disabledAttr()"
                      />
                    </a-checkbox>
                    <template v-if="!disabledAttr()">
                      <SvgIcon style="margin: 0; cursor: move" name="item" class="drag-item" prefix="icon-form" />
                      <a-button
                        type="primary"
                        shape="circle"
                        size="small"
                        style="margin-left: 10px"
                        @click="handleOptionsRemove(index)"
                      >
                        <template #icon>
                          <SvgIcon name="delete" prefix="icon-form" color="#fff" size="14" />
                        </template> </a-button
                    ></template>
                  </li>
                </template>
              </Draggable>
            </a-checkbox-group>
          </template>
          <div v-if="!disabledAttr()" class="flex justify-between" style="margin-top: 5px">
            <a-button type="link" size="small" @click="handleInsertOption"><PlusOutlined />添加选项</a-button>
            <a-button type="link" size="small" @click="showDict"><ImportOutlined />字典导入</a-button>
          </div>
          <check-box-extend
            v-if="data.type === 'select'"
            v-model:checked="data.options.multipleFlag"
            :disabled="disabledAttr()"
            @change="handleSelectModeChange"
          >
            允许选择多项
          </check-box-extend>
        </template>
      </a-form-item>

      <a-form-item v-if="data.options.attr === 1" label="是否自动带出业务值">
        <a-radio-group v-model:value="data.options.autoFillValueFlag" :disabled="disabledAttr()">
          <a-radio :value="0">否</a-radio>
          <a-radio :value="1">是</a-radio>
        </a-radio-group>
      </a-form-item>

      <a-form-item
        v-if="
          !data.options.autoFillValueFlag &&
          data.options.remote !== 2 &&
          hasKey('defaultValue') &&
          ['input', 'password', 'textarea', 'rate', 'switch', 'slider'].includes(data.type)
        "
        label="默认值"
      >
        <a-textarea v-if="data.type === 'textarea'" v-model:value="data.options.defaultValue" />
        <a-input v-else v-model:value="data.options.defaultValue" :disabled="disabledAttr()" />
      </a-form-item>

      <template v-if="data.type === 'date'">
        <a-form-item label="日期类型" :rules="{ required: true }">
          <a-select
            v-model:value="data.options.dateType"
            :get-popup-container="
              (triggerNode) => {
                return triggerNode.parentNode
              }
            "
            :disabled="disabledAttr()"
            @change="dataTypeChange"
          >
            <a-select-option :value="1">年</a-select-option>
            <a-select-option :value="2">年月</a-select-option>
            <a-select-option :value="3">年月日</a-select-option>
            <a-select-option :value="4">年月日 时</a-select-option>
            <a-select-option :value="5">年月日 时分</a-select-option>
            <a-select-option :value="6">年月日 时分秒</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="格式" :rules="{ required: true }">
          <a-select
            v-model:value="data.options.dateFormat"
            :get-popup-container="
              (triggerNode) => {
                return triggerNode.parentNode
              }
            "
            :disabled="disabledAttr()"
          >
            <a-select-option v-for="el in formatOption" :key="el.value" :value="el.value">
              {{ el.label }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <!-- <a-form-item label="绑定值格式">
        <a-input v-model:value="data.options.valueFormat" />
      </a-form-item> -->
      </template>

      <template v-if="!data.options.autoFillValueFlag && (data.type === 'date' || data.type === 'number')">
        <a-form-item label="默认值">
          <a-select
            v-model:value="data.options.defaultValueType"
            :get-popup-container="
              (triggerNode) => {
                return triggerNode.parentNode
              }
            "
            :disabled="disabledAttr()"
          >
            <a-select-option v-for="tempItem in defaultValueTypeArr" :key="tempItem.value" :value="tempItem.value">
              {{ tempItem.label }}
            </a-select-option>
          </a-select>
          <template v-if="data.options.defaultValueType === 1">
            <a-date-picker
              v-if="data.type === 'date'"
              v-model:value="data.options.defaultValue"
              style="width: 100%; margin-top: 10px"
              :picker="(datePickerType as any)"
              :format="(datePickerFormat as any)"
              :value-format="(datePickerFormat as any)"
              :show-time="datePickerShowTime"
              :placeholder="data.options.placeholder"
              :disabled="disabledAttr()"
            />
            <a-input-number
              v-else-if="data.type === 'number'"
              v-model:value="data.options.defaultValue"
              style="width: 100%; margin-top: 10px"
              min="-10000000"
              max="10000000"
              :disabled="disabledAttr()"
            />
          </template>
        </a-form-item>
      </template>

      <a-form-item
        v-if="
          data.type === 'radio' || (data.type === 'select' && data.options.remote === 1 && !data.options.multipleFlag)
        "
      >
        <a-button
          type="dashed"
          :disabled="!(data.options && data.options.options && data.options.options.length > 0)"
          @click="fieldLink"
        >
          选项联动设置
        </a-button>
      </a-form-item>

      <a-form-item v-if="data.type === 'upload'" label="附件数量限制（0表示不限制数量）">
        <a-input-number v-model:value="data.options.attachmentNumber" :min="0" :max="99" />
      </a-form-item>
      <a-form-item v-if="data.type === 'upload'">
        <a-checkbox v-model:checked="data.options.autoArchive">自动归档 </a-checkbox>
        <template v-if="data.options.autoArchive">
          <p class="text-gray-400">模板未关联项目文件夹目录，请在具体使用时设置归档路径</p>
          <a-button
            type="dashed"
            :disabled="
              myProgressConfig
                ? formBusinessLevel !== 4 && myProgressConfig.myProgressConfig.value.sourceType !== 'progressTemplate'
                : formBusinessLevel !== 4
            "
            @click="chooseArchivePath"
          >
            选择归档路径
          </a-button>
        </template>
      </a-form-item>

      <a-form-item v-if="hasKey('showLabel')" label="是否隐藏字段名称">
        <a-radio-group v-model:value="data.options.showLabel">
          <a-radio :value="0">不隐藏</a-radio>
          <a-radio :value="1">隐藏</a-radio>
        </a-radio-group>
      </a-form-item>

      <a-form-item v-if="hasKey('rules')" label="是否必填" name="required">
        <a-radio-group v-model:value="data.options.rules.required">
          <a-radio :value="false">非必填</a-radio>
          <a-radio :value="true">必填</a-radio>
        </a-radio-group>
      </a-form-item>

      <a-form-item v-if="data.type == 'input'" label="填写内容格式校验">
        <a-select
          v-model:value="data.options.format"
          :get-popup-container="
            (triggerNode) => {
              return triggerNode.parentNode
            }
          "
          :disabled="disabledAttr()"
          @change="formatChange"
        >
          <a-select-option :value="1">无格式限制</a-select-option>
          <a-select-option :value="2">仅允许填写手机号和座机</a-select-option>
          <a-select-option :value="3">仅允许填写邮箱</a-select-option>
        </a-select>
      </a-form-item>

      <a-form-item v-if="data.type == 'input' && data.options.format === 1" label="填写内容长度限制（请输入整数）">
        <a-input-number
          v-model:value="data.options.maxlength"
          :parser="parserNumber"
          :controls="false"
          :min="1"
          :max="200"
          :disabled="disabledAttr()"
        />
      </a-form-item>

      <a-form-item v-if="data.type == 'textarea'" label="填写内容长度限制（请输入整数）">
        <a-input-number
          v-model:value="data.options.maxlength"
          :parser="parserNumber"
          :controls="false"
          :min="1"
          :max="5000"
          :disabled="disabledAttr()"
        />
      </a-form-item>

      <a-form-item v-if="hasKey('max')" label="可输入数值范围（请输入整数）" :rules="{ required: true }">
        <a-input-number
          v-model:value.number="data.options.min"
          style="width: 110px"
          :min="-10000000"
          :max="10000000"
          :disabled="disabledAttr()"
        />
        ~
        <a-input-number
          v-model:value.number="data.options.max"
          style="width: 110px"
          :min="-10000000"
          :max="10000000"
          :disabled="disabledAttr()"
        />
      </a-form-item>

      <a-form-item v-if="hasKey('decimalPoint')" label="精确到小数点后位数">
        <a-input-number
          v-model:value.number="data.options.decimalPoint"
          style="width: 110px"
          :min="0"
          :max="2"
          :disabled="disabledAttr()"
        />
      </a-form-item>

      <!-- <a-form-item v-if="hasKey('step')" label="步长">
      <a-input-number v-model:value.number="data.options.step" :min="0" />
    </a-form-item> -->

      <!-- <a-form-item v-if="hasKey('checkedChildren')" label="选中时的内容">
        <a-input v-model:value="data.options.checkedChildren" />
      </a-form-item>

      <a-form-item v-if="hasKey('unCheckedChildren')" label="非选中时的内容">
        <a-input v-model:value="data.options.unCheckedChildren" />
      </a-form-item>

      <a-form-item v-if="hasKey('range')" label="双滑块模式">
        <a-switch v-model:checked="data.options.range" @change="handleSliderModeChange" />
      </a-form-item>

      <a-form-item v-if="hasKey('reverse')" label="反向坐标轴">
        <a-switch v-model:checked="data.options.reverse" />
      </a-form-item>

      <a-form-item v-if="hasKey('visibilityToggle')" label="是否显示切换按钮">
        <a-switch v-model:checked="data.options.visibilityToggle" checked-children="显示" un-checked-children="隐藏" />
      </a-form-item> -->

      <!-- <a-form-item v-if="hasKey('showCount')" label="是否显示字数">
      <a-switch v-model:checked="data.options.showCount" checked-children="显示" un-checked-children="隐藏" />
    </a-form-item> -->

      <!-- <a-form-item v-if="hasKey('autoSize')" label="是否自适应内容高度">
      <a-switch v-model:checked="data.options.autoSize" checked-children="是" un-checked-children="否" />
    </a-form-item> -->

      <!-- <a-form-item v-if="hasKey('rows') && !data.options.autosize" label="行数">
      <a-input-number v-model:value="data.options.rows" :min="0" />
    </a-form-item> -->

      <!-- <a-form-item v-if="hasKey('allowHalf')" label="是否允许半选">
        <a-switch v-model:checked="data.options.allowHalf" checked-children="是" un-checked-children="否" />
      </a-form-item> -->

      <!-- <a-form-item v-if="hasKey('showSearch')" label="单选模式是否可搜索">
        <a-switch v-model:checked="data.options.showSearch" checked-children="是" un-checked-children="否" />
      </a-form-item> -->

      <template v-if="data.type === 'img-upload'">
        <a-form-item label="是否支持多选">
          <a-switch v-model:checked="data.options.multiple" checked-children="是" un-checked-children="否" />
        </a-form-item>

        <a-form-item label="模式">
          <a-radio-group v-model:value="data.options.listType" button-style="solid">
            <a-radio-button value="text">text</a-radio-button>
            <a-radio-button value="picture">picture</a-radio-button>
            <a-radio-button value="picture-card">picture-card</a-radio-button>
          </a-radio-group>
        </a-form-item>

        <a-form-item label="文件参数名">
          <a-input v-model:value="data.options.name" />
        </a-form-item>

        <a-form-item label="上传地址">
          <a-input v-model:value="data.options.action" />
        </a-form-item>

        <a-form-item label="接受上传的文件类型(多个使用 , 隔开)">
          <a-input v-model:value="data.options.accept" />
        </a-form-item>

        <a-form-item label="最大上传数量">
          <a-input-number v-model:value.number="data.options.maxCount" :min="1" />
        </a-form-item>

        <a-form-item label="上传请求方法">
          <a-radio-group v-model:value="data.options.method" button-style="solid">
            <a-radio-button value="post">POST</a-radio-button>
            <a-radio-button value="put">PUT</a-radio-button>
            <a-radio-button value="get">GET</a-radio-button>
            <a-radio-button value="delete">DELETE</a-radio-button>
          </a-radio-group>
        </a-form-item>
      </template>

      <a-form-item v-if="data.type === 'cascader'" label="远端数据">
        <a-space direction="vertical">
          <a-input
            v-model:value="data.options.remoteConfig.url"
            :disabled="disabledAttr()"
            size="small"
            addon-before="远端地址"
          />
          <a-input
            v-model:value="data.options.remoteConfig.labelKey"
            :disabled="disabledAttr()"
            size="small"
            addon-before="标签"
          />
          <a-input
            v-model:value="data.options.remoteConfig.valueKey"
            :disabled="disabledAttr()"
            size="small"
            addon-before="值"
          />
          <a-input
            v-model:value="data.options.remoteConfig.children"
            :disabled="disabledAttr()"
            size="small"
            addon-before="子选项"
          />
        </a-space>
      </a-form-item>

      <template v-if="data.type === 'grid'">
        <a-form-item label="列配置项">
          <Draggable
            tag="ul"
            item-key="index"
            ghost-class="ghost"
            handle=".drag-item"
            :group="{ name: 'options' }"
            :list="data.columns[0]"
          >
            <template #item="{ element, index }">
              <li style="margin-bottom: 5px">
                <SvgIcon name="item" class="drag-item" prefix="icon-form" />
                <a-input-number
                  v-model:value="element.gridLayoutNumber"
                  placeholder="栅格值"
                  size="small"
                  :min="0"
                  :max="24"
                />
                <a-button
                  type="primary"
                  shape="circle"
                  size="small"
                  style="margin-left: 5px"
                  @click="handleOptionsRemove(index)"
                >
                  <template #icon>
                    <SvgIcon name="delete" prefix="icon-form" color="#fff" size="14" />
                  </template>
                </a-button>
              </li>
            </template>
          </Draggable>

          <div>
            <a-button type="link" size="small" @click="handleInsertColumn"> 添加列 </a-button>
          </div>
        </a-form-item>
      </template>

      <template v-if="data.type === 'fixedCombination'">
        <a-form-item label="列配置项">
          <!-- {{ data }} -->
          <li v-for="(element, index) in data.options.columns" :key="index" style="margin-bottom: 5px">
            <a-space>
              <SvgIcon name="item" prefix="icon-form" />
              <a-input-number
                v-model:value="element.gridLayoutNumber"
                placeholder="栅格值"
                size="small"
                :min="0"
                :max="24"
              />
              <a-input
                v-model:value="element.name"
                placeholder="字段名称"
                size="small"
                :min="0"
                :max="24"
                style="width: 140px"
              />
            </a-space>
            <!-- <a-button
              type="primary"
              shape="circle"
              size="small"
              style="margin-left: 5px"
              @click="handleOptionsRemove(index)"
            >
              <template #icon>
                <SvgIcon name="delete" prefix="icon-form" color="#fff" size="14" />
              </template>
            </a-button> -->
          </li>

          <!-- <div>
            <a-button type="link" size="small" @click="handleInsertColumn"> 添加列 </a-button>
          </div> -->
        </a-form-item>
      </template>

      <a-form-item label="是否可见" name="visibleFlag">
        <a-radio-group v-model:value="data.options.visibleFlag">
          <a-radio :value="1">是</a-radio>
          <a-radio :value="0">否</a-radio>
        </a-radio-group>
      </a-form-item>

      <a-form-item v-if="hasKey('readonlyFlag')" label="是否只读" name="readonlyFlag">
        <a-radio-group v-model:value="data.options.readonlyFlag">
          <a-radio :value="1">是</a-radio>
          <a-radio :value="0">否</a-radio>
        </a-radio-group>
      </a-form-item>

      <a-form-item v-if="isConfig()" label="是否允许删除" name="allowDeleteFlag">
        <a-radio-group v-model:value="data.options.allowDeleteFlag">
          <a-radio :value="1">是</a-radio>
          <a-radio :value="0">否</a-radio>
        </a-radio-group>
      </a-form-item>

      <a-form-item label="栅格布局" :rules="{ required: true }">
        <a-slider
          v-model:value="data.options.gridLayoutNumber"
          :max="24"
          :min="1"
          :marks="{ 1: '1', 6: '6', 8: '8', 12: '12', 24: '24' }"
        />
      </a-form-item>
    </a-form>
    <!--选项联动设置-->
    <OptionLinkageSetting ref="optionLinkRef" :option-list="optionList" :field-list="fieldList" @set-link="setLink" />
    <!-- 从数据字典导入数据 -->
    <DictSelect ref="DictSelectRef" @selected="selectedDictData" />
    <!--选择归档路径-->
    <SelectAchiveFolder
      ref="refSelectFolder"
      :tree-data-list="treeDataList"
      @onGetArchiveFolderId="getArchiveFolderId"
    ></SelectAchiveFolder>
  </div>
</template>

<script lang="ts">
import { computed } from '@vue/reactivity'
import { defineComponent, ref, Ref, watch, inject } from 'vue'
import Draggable from 'vuedraggable'
import OptionLinkageSetting from './components/OptionLinkageSetting.vue'
import { getCtmsArchiveFolder } from '@@/api/project/documentManage'
import {
  format,
  getDatePickerType,
  getDatePickerFormat,
  getDatePickerShowTime,
  defaultValueTypeArrFilter
} from '../config'
import DictSelect from './DictSelect.vue'
import { PlusOutlined, ImportOutlined } from '@ant-design/icons-vue'
import { isConfig } from '@@/utils/index'
import { message } from 'ant-design-vue'
import SelectAchiveFolder from '@@/components/TaskKanban/FileList/components/SelectAchiveFolder.vue'

export default defineComponent({
  name: 'AntdWidgetConfig',
  components: {
    Draggable,
    OptionLinkageSetting,
    DictSelect,
    PlusOutlined,
    ImportOutlined,
    SelectAchiveFolder
  },
  props: {
    select: {
      type: Object
    },
    allData: {
      type: Object,
      default: () => {}
    },
    formBusinessLevel: {
      type: Number,
      default: 0
    }
  },
  emits: ['update:select'],
  setup(props, context) {
    const data = ref<any>(props.select)
    const optionList = ref()
    const fieldList = ref<any[]>([])

    /** 接收从项目进度模板的编辑页面传过来的数据
     * 用途：1、判断入口是否为进度模板，从进度模板进入时的自动归档路径可选择归档路径
     *      2、接收进度模板选择的归档目录数据
     */
    const myProgressConfig: any = inject('myProgressConfig')

    watch(
      () => props.select,
      (val) => {
        if (val) {
          data.value = val
          data.value.columns = data.value.columns || []
          optionList.value = data.value.options.options
          if (val.parentKey) {
            const gridItem = props.allData.list.find((item) => item.key === val.parentKey)
            const fields = gridItem.columns[0].filter((item: any) => item.list[0]?.key !== data.value?.key)
            fieldList.value = fields.map((el: any) => {
              return el.list[0]
                ? {
                    label: el.list[0].fieldName,
                    model: el.list[0].key,
                    visibleFlag: el.list[0].options.visibleFlag
                  }
                : {}
            })
          } else {
            const fields = props.allData.list.filter((item: any) => item.key !== data.value?.key)
            fieldList.value = fields.map((el: any) => {
              return {
                label: el.fieldName,
                model: el.key,
                visibleFlag: el.options.visibleFlag
              }
            })
          }
          setDefaultValueTypeArr()
          setDateFormatOption()
        }
      }
    )

    watch(data, (val) => context.emit('update:select', val))

    const datePickerType: any = computed(() => {
      return getDatePickerType(data.value.options.dateType)
    })

    const datePickerFormat: any = computed(() => {
      return getDatePickerFormat(data.value.options.dateType, data.value.options.dateFormat).label
    })

    const datePickerShowTime: any = computed(() => {
      return getDatePickerShowTime(data.value.options.dateType)
    })

    const formatOption = ref(format[3])
    const optionLinkRef = ref()

    const hasKey = (key: string) => Object.keys(data.value.options).includes(key)

    const handleInsertColumn = () => {
      data.value.columns.push({
        gridLayoutNumber: 0,
        list: []
      })
    }

    // 切换数据来源
    const remoteChange = () => {
      data.value.options.defaultOptions = []
    }

    // 添加选项
    const DictSelectRef = ref()
    const showDict = () => {
      DictSelectRef.value.show()
    }

    // 数据字典数据来了
    const selectedDictData = (list) => {
      data.value.options.options = list
    }

    const handleInsertOption = () => {
      const index = data.value.options.options.length + 1
      data.value.options.options.push({
        label: `Option ${index}`,
        value: `${index}`
      })
    }
    // 删除选项
    const handleOptionsRemove = (index: number) => {
      if (data.value.type === 'grid') {
        data.value.columns.splice(index, 1)
      } else {
        data.value.options.options.splice(index, 1)
      }
    }

    const handleSelectModeChange = () => {
      data.value.options.defaultValue = ''
      data.value.options.defaultOptions = []
      if (data.value.options.multipleFlag) {
        // 允许选择多项时，清空选项联动设置
        data.value.options.linkContent = null
      }
    }

    const handleSliderModeChange = (checked: boolean) => {
      checked ? (data.value.options.defaultValue = [0, 0]) : (data.value.options.defaultValue = 0)
    }

    const parserNumber = (str) => {
      return /^\d+$/.test(str) ? str : parseInt(str)
    }

    const formatChange = (val) => {
      // 1： 无格式限制；2：手机号；3：邮箱
      if (val === 1) {
        data.value.options.rules.type = 'string'
        data.value.options.rules.pattern = ''
      }
      if (val === 2) {
        data.value.options.rules.type = 'string'
        data.value.options.rules.pattern = /^1(3\d|4[5-9]|5[0-35-9]|6[567]|7[0-8]|8\d|9[0-35-9])\d{8}$/
      }
      if (val === 3) {
        data.value.options.rules.type = 'email'
        data.value.options.rules.pattern = ''
      }
    }

    const dataTypeChange = (val) => {
      formatOption.value = format[val]
      data.value.options.dateFormat = format[val][0].value
    }

    const fieldLink = () => {
      optionLinkRef.value.show(data.value.options.linkContent)
    }
    const treeDataList: Ref<any> = ref([])
    // 获取树数据
    const reloadTreeData = () => {
      getCtmsArchiveFolder({ projectId: sessionStorage.getItem('__projectId') })
        .then((res) => {
          treeDataList.value = res ? [res] : []
          addFolderKey(treeDataList.value, 'archiveFolderId')
        })
        .catch(() => {})
    }
    console.log(props.formBusinessLevel, '-props.formBusinessLevel')
    if (props.formBusinessLevel === 4) {
      reloadTreeData()
    }
    const refSelectFolder = ref()
    // 选择归档路径
    const chooseArchivePath = () => {
      if (!treeDataList.value || !treeDataList.value.length) {
        return message.warning('请先选择文件夹目录')
      }
      refSelectFolder.value.show(data.value.options)
    }

    // 添加树组件所需的key
    const addFolderKey = (list, key) => {
      list.forEach((item) => {
        if (item[key]) {
          item.folderKey = item[key]
        }
        if (item.children && item.children.length) {
          addFolderKey(item.children, key)
        }
      })
    }
    if (myProgressConfig) {
      treeDataList.value = myProgressConfig.formData.value.folder ? [myProgressConfig.formData.value.folder] : []
      addFolderKey(treeDataList.value, 'speedFolderId')
    }
    // 获取归档文档id
    const getArchiveFolderId = ({ checkedKey, pathName }) => {
      data.value.options.archiveFolderId = checkedKey
      data.value.options.folderName = pathName
    }
    // 选择归档路径
    // const chooseArchivePath = () => {
    //   console.log(1)
    // }

    const setLink = (associatedFields) => {
      data.value.options.linkContent = associatedFields
    }

    /**
     * 禁用业务字段的相关属性
     */
    const disabledAttr = () => {
      return data.value.options.attr === 1
    }

    const defaultValueTypeArr = ref([] as any[])

    /**
     * 设置默认值数组
     */
    const setDefaultValueTypeArr = () => {
      defaultValueTypeArr.value = defaultValueTypeArrFilter(data.value.fieldType)
    }

    /**
     * 设置日期格式选项
     */
    const setDateFormatOption = () => {
      if (data.value.type !== 'date') {
        return
      }
      if (data.value.options.dateType) {
        // 根据日期类型给格式赋值
        formatOption.value = format[data.value.options.dateType]
      } else {
        return
      }
      if (data.value.options.dateFormat) {
        return
      }
      // 日期格式为空时，默认设置第一选项
      data.value.options.dateFormat = format[data.value.options.dateType][0].value
    }

    return {
      data,
      formatOption,
      optionLinkRef,
      DictSelectRef,
      optionList,
      fieldList,
      datePickerType,
      datePickerFormat,
      datePickerShowTime,
      hasKey,
      handleInsertColumn,
      handleInsertOption,
      handleOptionsRemove,
      handleSelectModeChange,
      handleSliderModeChange,
      parserNumber,
      formatChange,
      dataTypeChange,
      fieldLink,
      setLink,
      showDict,
      selectedDictData,
      remoteChange,
      isConfig,
      disabledAttr,
      defaultValueTypeArr,
      chooseArchivePath,
      treeDataList,
      getArchiveFolderId,
      refSelectFolder,
      myProgressConfig
    }
  }
})
</script>
